import { defineStore } from 'pinia'
import { getLocalStorage, setLocalStorage, removeLocalStorage } from 'vue3-common/utils/storageUtil'
import { ILoginForm } from 'vue3-common'
import { ISession, IUser } from '@/types/auth'
import { queryUserApi, updateUserApi } from '@/apis/user.ts'
import { ImagePathEnum } from '@/types'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {
      id: 0,
      accountId: 0,
      accountName: '',
      username: '',
      gender: 0,
      idNumber: '',
      phoneNumber: '',
      email: '',
      birthDate: '',
      avatar: '',
      description: '',
      area: ['', ''],
      address: '',
      job: '',
      tags: []
    } as IUser,
    userImagePath: ImagePathEnum.USER
  }),

  actions: {
    setLoginForm(loginForm: ILoginForm) {
      setLocalStorage('loginForm', JSON.stringify(loginForm))
    },
    getLoginForm() {
      return getLocalStorage('loginForm')
    },
    removeLoginForm() {
      removeLocalStorage('loginForm')
    },
    handleSession(session: ISession) {
      this.setToken(session.saToken.tokenValue)
      this.setUserId(session.userInfo.id)
      this.userInfo = session.userInfo
    },
    async queryUser() {
      this.userInfo = await queryUserApi(Number(this.getUserId()))
    },
    async updateUser() {
      await updateUserApi(this.userInfo.id, this.userInfo)
    },
    async updateAccountPassword(oldPassword: string, newPassword: string) {
      console.log(this.userInfo.accountId)
      // await updateAccountPasswordApi(this.userInfo.accountId, oldPassword, newPassword)
    },
    setToken(token: string) {
      setLocalStorage('token', token)
    },
    getToken() {
      return getLocalStorage('token')
    },
    setUserId(userId: number) {
      setLocalStorage('userId', String(userId))
    },
    getUserId() {
      return getLocalStorage('userId')
    },
    setAccount(accountName: string) {
      setLocalStorage('account', accountName)
    },
    getAccount() {
      return getLocalStorage('account')
    },
    removeAll() {
      removeLocalStorage('token')
      removeLocalStorage('account')
    }
  }
})
